import { invoke } from "@tauri-apps/api/tauri";
import { getClient, Body, ResponseType } from '@tauri-apps/api/http';
import { cli } from "@tauri-apps/api";

let greetInputEl: HTMLInputElement | null;
let greetMsgEl: HTMLElement | null;
let rpcMsgEl: HTMLElement | null;

async function greet() {
  console.log("calling greet()---1");
  if (greetMsgEl && greetInputEl && rpcMsgEl) {
    console.log("calling greet()---2");
    // Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
    greetMsgEl.textContent = await invoke(
      "plugin:datarpc|greet"
      // "greet"
      , {
        name: greetInputEl.value,
      });

    const client = await getClient();

    rpcMsgEl.textContent= await client.post('http://localhost:5678/api/login', {
      payload: Body.json({
        "username": "demo1",
        "pwd": "welcome"
      }),
      // in this case the server returns a simple string
      type: "Json",
    }).then((rs) => {
      console.log("client.post got reponse=", rs);
      return JSON.stringify(rs);
    }

    );

  }
}

window.addEventListener("DOMContentLoaded", () => {
  greetInputEl = document.querySelector("#greet-input");
  greetMsgEl = document.querySelector("#greet-msg");
  rpcMsgEl = document.querySelector("#rpc-msg");
  document.querySelector("#greet-form")?.addEventListener("submit", (e) => {
    e.preventDefault();
    greet();
  });
});
